package com.example.demo;

import com.example.demo.common.ResultAjax;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-06-03
 * Time: 18:41
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    /**
     * 判断内容是否需要重写
     * 返回 true 表示重写
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // return false; // 默认不会使用同一返回
        return true;
    }

    @Autowired
    private ResultAjax resultAjax;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 执行重写方法, 同一数据的格式.
     *
     * @param body 传来的没有处理的原始数据
     *             TODO : 作为一个保底策略, 防止其他人忘记返回统一的数据格式给前端
     */
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType, Class selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {

        // 判读数据格式是否符合预定要求
        if (body instanceof ResultAjax) {
            return body;
        }

        // 不符合预期的格式, 强制进行自定义的格式返回
        resultAjax.setCode(200);
        resultAjax.setDate(body);
        resultAjax.setMes("");

//        if(body instanceof String) {
//            // 将 ResultAJax 转为 JSON 字符串
//            return objectMapper.writeValueAsString(resultAjax);
//        }

        return resultAjax;
    }
}
